const express = require('express');

const db = require('../db')

const router = express.Router();


// -----------------------------------------------------获取历史记录--------------------------------------------------------
router.get('/get_history', (req, res) => {
	const {
		limit,
		page
	} = req.query
	const {user_id} = req.user
	let start;
	let sql = `select * from search_history where user_id = '${user_id}' order by create_time desc`
	if (limit && page) {
		start = ` limit ${(page-1)*limit},${limit}`
		sql += start;
	}
	console.log(sql);
	db(sql, (err, data) => {
		if (err) {
			res.send({
			    code:-1,
			    msg:err.sqlMessage,
			})
			throw err
		}
		res.send({
			code: 1,
			msg: '获取成功',
			data: {
				list: data
			}

		})
	})
})

// -----------------------------------------------------添加历史记录--------------------------------------------------------
router.post('/add_history',(req,res)=>{
    const {content}=req.body;
		const {user_id} = req.user;
		const now = Date.parse(new Date())/1000
    db(`insert into search_history(user_id,content,create_time) values ('${user_id}','${content}',${now})`,(err,data)=>{
        if (err) {
            res.send({
                code:-1,
                msg:err.sqlMessage,
            })
            throw err ;
        }
        res.send({
            code:1,
            msg:'添加成功！'
        })
    })
})

// -----------------------------------------------------删除历史记录--------------------------------------------------------
router.post('/del_history',(req,res)=>{
		const {user_id} = req.user;
    db(`delete from search_history where user_id ='${user_id}'`,(err,data)=>{
        if (err) {
            res.send({
                code:-1,
                msg:err.sqlMessage,
            })
            throw err ;
        }
        res.send({
            code:1,
            msg:'删除成功！'
        })
    })
})






module.exports = router
